package app

import (
	"a-admin/web/resp"
	"a-app/domain/entity"
	"a-app/service"
	"a-common/myerr"

	"fmt"
	"sync"

	"github.com/gofiber/fiber/v2"
)

var (
	appBalanceControllerTemp *AppBalanceController
	appBalanceService        = service.NewAppBalanceService()
	appBalanceControllerOnce sync.Once
)

type AppBalanceController struct{}

func NewAppBalanceController() *AppBalanceController {
	appBalanceControllerOnce.Do(func() {
		appBalanceControllerTemp = &AppBalanceController{}
	})
	return appBalanceControllerTemp
}

// List 分页
func (m *AppBalanceController) List(c *fiber.Ctx) error {
	var args entity.AppBalanceDto
	if err := c.QueryParser(&args); err != nil {
		return myerr.ERR_SYS_ARGS
	}
	err := args.Validator()
	if err != nil {
		return err
	}

	// 查询
	pageVo, err := appBalanceService.List(&args)
	if err != nil {
		return err
	}
	return resp.Resp(c, pageVo)
}

// Del 删
func (m *AppBalanceController) Del(c *fiber.Ctx) error {
	ids := c.Params("ids")
	if ids == "" {
		return myerr.ERR_SYS_ARGS
	}
	_, err := appBalanceService.Del(ids)
	if err != nil {
		return err
	}
	return resp.Ok(c)
}

// Get 查
func (m *AppBalanceController) Get(c *fiber.Ctx) error {
	id := c.Params("id")
	if id == "" {
		return myerr.ERR_SYS_ARGS
	}
	data, err := appBalanceService.Get(id)
	if err != nil {
		return err
	}
	return resp.Resp(c, data)
}

// Add 增
func (m *AppBalanceController) Add(c *fiber.Ctx) error {
	var args entity.AppBalanceDto
	if err := c.BodyParser(&args); err != nil {
		return myerr.ERR_SYS_ARGS
	}
	user := resp.GetUser(c)
	args.CreatedBy = user.Account

	_, err := appBalanceService.Add(&args)
	if err != nil {
		return err
	}
	return resp.Ok(c)
}

// Edit 改
func (m *AppBalanceController) Edit(c *fiber.Ctx) error {
	var args entity.AppBalanceDto
	if err := c.BodyParser(&args); err != nil {
		return myerr.ERR_SYS_ARGS
	}
	user := resp.GetUser(c)
	args.UpdatedBy = user.Account

	_, err := appBalanceService.Edit(&args)
	if err != nil {
		return err
	}
	return resp.Ok(c)
}

// Export 导出
func (m *AppBalanceController) Export(c *fiber.Ctx) error {
	var args entity.AppBalanceDto
	if err := c.QueryParser(&args); err != nil {
		return myerr.ERR_SYS_ARGS
	}

	if args.PageNum < 1 {
		args.PageNum = 1
	}
	if args.PageSize < 1 {
		args.PageSize = 10
	}

	f, err := appBalanceService.Export(&args)
	if err != nil {
		return err
	}

	c.Set("Content-Disposition", fmt.Sprintf(`attachment; filename="%s"`, "账户余额表"))
	err = f.Write(c.Response().BodyWriter())
	if err != nil {
		return err
	}
	return nil
}
